/*
 * Copyright 2011 PA Consulting Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.prodeagle.java.counters;

import java.util.HashMap;
import java.util.Map;

/**
 * A Batch Counter, allowing you to create and increment multiple counters
 * in one commit process.
 * 
 * To use, initalise Batch:
 * <code>BatchCounter batchCounter = new BatchCounter();</code>
 * 
 * Then increment several counters:
 * <code>batchCounter.increment("CounterA");
 * batchCounter.increment("CounterB", 2); //increment CounterB by 2</code>
 * 
 * Then finally commit the counters:
 * <code>batchCounter.commit();</code>
 * 
 * @author Edward Hartwell Goose
 *
 */
public class BatchCounter {

	/**
	 * The Map of counter names to values that
	 * will be committed
	 */
	private Map<String, Long> pendingCounters;
	
	public BatchCounter() {
		pendingCounters = new HashMap<String, Long>();
	}
	
	/**
	 * Increment a named counter in a batch by 1
	 * @param name - the name of the counter to increment by 1
	 */
	public void increment(String name) {
		increment(name, 1);
	}

	/**
	 * Increment a batch counter by a value, delta
	 * @param name - the name of the counter to increment
	 * @param delta - the amount to increment by (can be negative)
	 */
	public void increment(String name, long delta) {
		Long currentValue = this.pendingCounters.get(name);
		if (null == currentValue) {
			//if this counter hasn't already been incremented as part of this batch, initialise the value to 0
			currentValue = 0L; 
		}
		this.pendingCounters.put(name, currentValue + delta);
	}
	
	/**
	 * Commit all the pending batch counters
	 * 
	 * ProdEagle stats will be stored in the process.
	 */
	public void commit() {
		this.commit(true);
	}
	
	/**
	 * Commit the values of several counters at once to memcache 
	 * 
	 * @param saveProdEagleStats - whether to increment the internal ProdEagle stats or not
	 */
	public void commit(boolean saveProdEagleStats) {
		if (null != this.pendingCounters && this.pendingCounters.size() != 0) {
			Counter.incrementBatch(this.pendingCounters, saveProdEagleStats);
		}
		
		//reset the pending counters so this batch can be reused
		this.pendingCounters = new HashMap<String, Long>();
	}
	
	@Override
	public String toString() {
		if (null == pendingCounters || pendingCounters.size() == 0) {
			return "No pending counters";
		} else {
			return "Pending counters: " + pendingCounters.toString();
		}
	}
}